import { RootState } from '@/types/store'
import { Input, NavBar, TextArea } from 'antd-mobile'
import { InputRef } from 'antd-mobile/es/components/input'
import { TextAreaRef } from 'antd-mobile/es/components/text-area'
import { useEffect, useRef, useState } from 'react'
import { useSelector } from 'react-redux'

import styles from './index.module.scss'
type Props = {
  hideInput: () => void
  type: '' | 'name' | 'intro'
  onUpdata: (key: string, value: string) => void
}
const EditInput = ({ hideInput, type, onUpdata }: Props) => {
  const { profile } = useSelector((state: RootState) => state.profile)
  const name = type === 'name' ? '暱稱' : '簡介'
  const [value, setValue] = useState(type === 'name' ? profile.name : profile.intro)
  const inputRef = useRef<InputRef>(null)
  const textRef = useRef<TextAreaRef>(null)
  useEffect(() => {
    if (type === 'name') {
      inputRef.current?.focus()
    } else {
      textRef.current?.focus()
      document.querySelector('textarea')?.setSelectionRange(-1, -1)
    }
  }, [type])
  return (
    <div className={styles.root}>
      <NavBar
        className='navbar'
        onBack={hideInput}
        right={
          <span className='commit-btn' onClick={() => onUpdata(type, value)}>
            提交
          </span>
        }>
        編輯{name}
      </NavBar>

      <div className='edit-input-content'>
        <h3>{name}</h3>

        {type === 'name' ? (
          <div className='input-wrap'>
            <Input
              placeholder='請輸入暱稱'
              className='input-wrap'
              value={value}
              onChange={e => setValue(e)}
              ref={inputRef}
            />
          </div>
        ) : (
          <TextArea
            className='textarea'
            placeholder='请输入简介'
            maxLength={100}
            showCount
            value={value || ''}
            onChange={e => setValue(e)}
            ref={textRef}></TextArea>
        )}
      </div>
    </div>
  )
}

export default EditInput
